// Package api 的营销模块：提供立减金发放与发放记录查询等接口。
package api

import (
	"encoding/json"
	"net/http"
	"strconv"
	"time"

	"github.com/we-pay-kit/we-pay-kit/internal/db"
	"github.com/we-pay-kit/we-pay-kit/internal/repository"
	"github.com/we-pay-kit/we-pay-kit/internal/wechat"
)

type MarketingHandler struct {
	cRepo *repository.CouponIssueRepository
	wcli  wechat.API
}

func NewMarketingHandler(w wechat.API) *MarketingHandler {
	database := db.GetDB()
	return &MarketingHandler{cRepo: repository.NewCouponIssueRepository(database), wcli: w}
}

// POST /api/v1/marketing/cash-coupons/send
func (h *MarketingHandler) SendCashCoupon(w http.ResponseWriter, r *http.Request) {
	var in struct {
		ActivityID   int64   `json:"activity_id"`
		PackageID    int64   `json:"package_id"`
		PhoneNumber  string  `json:"phone_number"`
		UserID       *string `json:"user_id"`
		CouponID     string  `json:"coupon_id"`
		CouponAmount float64 `json:"coupon_amount"`
		OpenID       string  `json:"openid"`
		SendName     string  `json:"send_name"`
		Remark       string  `json:"remark"`
	}
	if err := json.NewDecoder(r.Body).Decode(&in); err != nil {
		http.Error(w, err.Error(), http.StatusBadRequest)
		return
	}
	req := wechat.SendCashCouponRequest{CouponID: in.CouponID, OpenID: in.OpenID, SendName: in.SendName, Remark: in.Remark}
	resp, err := h.wcli.SendCashCoupon(req)
	status := "FAILED"
	var failReason *string
	if err == nil && resp != nil && (resp.ResultCode == "SUCCESS" || resp.ReturnCode == "SUCCESS") {
		status = "SUCCESS"
	} else if err != nil {
		s := err.Error()
		failReason = &s
	} else if resp != nil && resp.ErrCodeDes != "" {
		s := resp.ErrCodeDes
		failReason = &s
	}
	_, _ = h.cRepo.Create(r.Context(), &repository.CouponIssue{ActivityID: in.ActivityID, PackageID: in.PackageID, PhoneNumber: in.PhoneNumber, UserID: in.UserID, CouponID: in.CouponID, CouponAmount: in.CouponAmount, IssueTime: time.Now(), Status: status, FailReason: failReason})
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(resp)
}

// GET /api/v1/marketing/cash-coupons/list?activity_id=1&limit=20&offset=0
func (h *MarketingHandler) ListCashCouponIssues(w http.ResponseWriter, r *http.Request) {
	q := r.URL.Query()
	aid, _ := strconv.ParseInt(q.Get("activity_id"), 10, 64)
	limit, _ := strconv.Atoi(q.Get("limit"))
	offset, _ := strconv.Atoi(q.Get("offset"))
	list, err := h.cRepo.ListByActivity(r.Context(), aid, limit, offset)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}
	w.Header().Set("Content-Type", "application/json")
	_ = json.NewEncoder(w).Encode(list)
}
